﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace DCT.Service.Restriction.Utility.Config
{
    public class ObjectConfigParser : IConfigParser
    {
        private IDictionary<string, object> objectconfig;

        public ObjectConfigParser()
        {
            this.objectconfig = new Dictionary<string, object>();
        }

        public IConfigParser Load(object config)
        {
            if (config == null || !(config is IDictionary<string, object>))
            {
                throw new ArgumentException("config不能为空，且必须为IDictionary<string, object>类型");
            }

            this.objectconfig = config as IDictionary<string, object>;
            return this;
        }

        public IDictionary<string, object> Raw
        {
            get { return this.objectconfig; }
        }

        public IConfigParser Clear()
        {
            this.objectconfig.Clear();
            return this;
        }

        public string ParseToString()
        {
            return JsonConvert.SerializeObject(this.objectconfig, Formatting.Indented);
        }

        public IEnumerable<KeyValuePair<string, string>> GetKV(string key)
        {
            return this.GetObjectVal<IEnumerable<KeyValuePair<string, string>>>(key, null);
        }

        public IEnumerable<IEnumerable<KeyValuePair<string, string>>> GetListKV(string key)
        {
            return this.GetObjectVal<IEnumerable<IEnumerable<KeyValuePair<string, string>>>>(key, null);
        }

        public IEnumerable<string> GetListVal(string key)
        {
            return this.GetObjectVal<IEnumerable<string>>(key, null);
        }

        public string GetVal(string key, string defaultVal)
        {
            return this.GetObjectVal(key, defaultVal);
        }

        public void SetKV(string key, IEnumerable<KeyValuePair<string, string>> kv)
        {
            this.objectconfig[key] = kv;
        }

        public void SetListKV(string key, IEnumerable<IEnumerable<KeyValuePair<string, string>>> kvList)
        {
            this.objectconfig[key] = kvList;
        }

        public void SetListVal(string key, IEnumerable<string> listVal)
        {
            this.objectconfig[key] = listVal;
        }

        public void SetVal(string key, string val)
        {
            this.objectconfig[key] = val;
        }

        private T GetObjectVal<T>(string key, T defaultVal)
            where T : class
        {
            T t = null;
            object obj = null;
            if (this.objectconfig != null
                && this.objectconfig.TryGetValue(key, out obj)
                && (obj is T))
            {
                t = (obj as T);
            }
            if (t == null)
            {
                t = defaultVal;
            }
            return t;
        }
    }
}
